<route lang='jsonc' type='page'>{
    "layout": "page",
    "style": {
        "navigationBarTitleText": "设置地址",
        "navigationStyle": "custom"
    }
}</route>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { useMessage } from 'wot-design-uni'
import { computed, reactive, ref, watch } from 'vue'
import { addAddress, editAddress, getAddressInfo,delAddress } from '@/api/address'
import uniDataPicker from '@dcloudio/uni-ui/lib/uni-data-picker/uni-data-picker.vue'
import areaData from '@/static/area-data.json'
const message = useMessage()

const title = ref('添加收货地址')
const left = ref(true)
const headerRef = ref()

// 使用响应式对象
const form = reactive({
    receiver: '',
    mobile: '',
    provinceCode: '',
    cityCode: '',
    countyCode: '',
    province: '',
    city: '',
    county: '',
    addressDetail: '',
    isDefault: 0
})

// 计算属性 - 表单验证
const isFormValid = computed(() => {
    return form.receiver.trim() !== '' &&
        form.mobile.trim() !== '' &&
        form.provinceCode.trim() !== '' &&
        form.cityCode.trim() !== '' &&
        form.countyCode.trim() !== '' &&
        form.addressDetail.trim() !== ''
})

async function fetchAddressInfo(id: string) {
    try {
        const res = await getAddressInfo(id)
        console.log('获取收货地址信息结果:', res)
        if (res.code === 10000) {
            const data = res.data
            console.log('收货地址数据:', data)

            form.receiver = data.receiver
            form.mobile = data.mobile
            form.provinceCode = data.provinceCode
            form.cityCode = data.cityCode
            form.countyCode = data.countyCode
            form.province = data.province
            form.city = data.city
            form.county = data.county
            form.addressDetail = data.addressDetail
            form.isDefault = Number(data.isDefault)

            console.log('修复后的表单数据:', form)
        }
    } catch (error) {
        console.error('获取收货地址信息失败:', error)
        uni.showToast({ title: '获取收货地址信息失败', icon: 'none' })
    }
}

watch(isFormValid, (valid) => {
    if (headerRef.value) {
        const rightTextEl = headerRef.value.$el.querySelector('.text-28rpx')
        if (rightTextEl) {
            rightTextEl.style.color = valid ? '#16C2A3' : '#ccc'
        }
    }
})

// 计算按钮颜色
const buttonColor = computed(() => {
    return isFormValid.value ? '#16C2A3' : '#ccc'
})

// 实时校验
const checkForm = () => {
    // 空函数，计算属性会自动更新
}

// 地区选择变化处理
const onAreaChange = (e) => {
    const value = e.detail.value
    if (value && value.length >= 3) {
        form.provinceCode = value[0].value
        form.cityCode = value[1].value
        form.countyCode = value[2].value
        form.province = value[0].text
        form.city = value[1].text
        form.county = value[2].text
    } else {
        // 如果选择不完整，清空相关字段
        form.provinceCode = ''
        form.cityCode = ''
        form.countyCode = ''
        form.province = ''
        form.city = ''
        form.county = ''
    }
    checkForm() // 触发表单校验
}

// 保存逻辑
const handleSave = async () => {
    // 在编辑模式下，确保数据已加载完成
    if (title.value === '编辑收货地址' && addressId.value) {
        // 等待数据加载完成，通过检查receiver字段是否已填充
        if (!form.receiver) {
            uni.showToast({ title: '数据加载中，请稍后...', icon: 'none' })
            return
        }
    }
    
    if (!isFormValid.value) {
        return uni.showToast({ title: '请完善信息', icon: 'none' })
    }

    const submitData = {
        receiver: form.receiver,
        mobile: form.mobile,
        provinceCode: form.provinceCode,
        cityCode: form.cityCode,
        countyCode: form.countyCode,
        addressDetail: form.addressDetail,
        isDefault: form.isDefault
    }

    try {
        let res
        if (title.value === '编辑收货地址' && addressId.value) {
            // 编辑模式
            res = await editAddress({ id: addressId.value, data: submitData })
        } else {
            // 添加模式
            res = await addAddress(submitData)
        }

        if (res.code === 10000) {
            uni.showToast({ title: '保存成功', icon: 'success' })
            setTimeout(() => {
                uni.navigateBack({ delta: 1 })
            }, 0)
        } else {
            uni.showToast({ title: res.data.message || '保存失败', icon: 'none' })
        }
    } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({ title: '保存失败', icon: 'none' })
    }
}

// 获取页面参数
const addressId = ref('')
onLoad((options) => {
    title.value = (options?.type === 'edit') ? '编辑收货地址' : '添加收货地址'
    addressId.value = options?.id || ''

    // 如果是编辑模式，获取收货地址信息
    if (options?.type === 'edit' && addressId.value) {
        fetchAddressInfo(addressId.value)
    }
})

// 删除收货地址
function confirm() {
    message
        .confirm({
            msg: '确定删除该收货地址',
            title: '删除'
        })
        .then(() => {
            // 这里需要调用删除接口
            delAddress(addressId.value).then((res) => {
                if (res.code === 10000) {
                    uni.showToast({ title: '删除成功', icon: 'success' })
                    setTimeout(() => {
                        uni.navigateBack({ delta: 1 })
                    }, 0)
                }
            })
                .catch(() => {
                    uni.showToast({ title: '删除失败', icon: 'none' })
                })
        })
}
const gotosave = () => {
    uni.navigateBack()
}

</script>

<template>
    <view class="add-address">
        
        <view @click="handleSave" style="position: absolute;right: 20rpx;top: 30rpx;color:#16c2a3" >
            保存
        </view>
        <view style="display: flex;align-items: center;justify-content: left;height: 80rpx;margin-bottom:30rpx">
            <image src="/static/image/return@1x.png" @click="gotosave" style="width: 40rpx;height: 40rpx;margin-left:30rpx;margin-top:30rpx;"></image>

            <view style="margin-left:200rpx;margin-top:30rpx;">设置地址</view>
        </view>

        <!-- 表单区域 -->
        <view class="form-wrapper">
            <!-- 收货人姓名 -->
            <view class="form-row">
                <view class="form-label">收货人姓名</view>
                <input class="form-input" type="text" placeholder="请填写收货人姓名" v-model="form.receiver"
                    @input="checkForm" />
            </view>

            <!-- 联系方式 -->
            <view class="form-row">
                <view class="form-label">联系方式</view>
                <input class="form-input" type="number" placeholder="请填写联系方式" v-model="form.mobile"
                    @input="checkForm" />
            </view>

            <!-- 地区选择 -->
            <view class="form-row">
                <view class="form-label">所在地区</view>
                <uni-data-picker :localdata="areaData" placeholder="请选择所在地区" popup-title="请选择所在地区"
                    v-model="form.provinceCode" @change="onAreaChange" />
            </view>

            <!-- 详细地址 -->
            <view class="form-row">
                <view class="form-label">详细地址</view>
                <input class="form-input" type="text" placeholder="请填写详细地址" v-model="form.addressDetail"
                    @input="checkForm" />
            </view>

            <!-- 是否默认 -->
            <view class="form-row">
                <view class="form-label">设为默认地址</view>
                <wd-checkbox v-model="form.isDefault" :true-value="1" :false-value="0"
                    checked-color="#16C2A3" style="margin-right: 440rpx;"></wd-checkbox>

            </view>

            <view v-if="addressId" style="width: 100%;text-align: center;height: 80rpx;line-height: 80rpx;
            background-color: #b2b3b6;color: #ffffff;font-size:30rpx;border-radius: 50rpx;margin-top: 100rpx;" @click="confirm">
                删除地址
            </view>
            <wd-message-box />
        </view>
    </view>
</template>

<style lang="scss" scoped>
.add-address {
    background-color: #fff;
    min-height: 100vh;

    // 表单容器
    .form-wrapper {
        padding: 30rpx;

        // 每行布局
        .form-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 30rpx;

            .form-label {
                font-size: 28rpx;
                color: #333;
                width: 180rpx; // 固定宽度对齐
            }

            .form-input {
                flex: 1;
                height: 60rpx;
                line-height: 60rpx;
                font-size: 26rpx;
                color: #999;
                border-bottom: 1px solid #eee; // 下划线
            }
        }
    }
}
</style>